﻿using System;
using System.Collections.Generic;
using System.Text;
using log4net;

namespace BaseBL
{
    public abstract class Logger
    {
        private ILog logger;

        protected Logger()
        {
            log4net.Config.XmlConfigurator.Configure();
            logger = LogManager.GetLogger(GetLoggerName());
        }
        
        public abstract string GetLoggerName();

        public void LogDebug(string message)
        {
            if (logger.IsDebugEnabled)
            {
                ThreadContext.Properties["UId"] = GetUniqueId();
                logger.Debug(message);
            }
        }

        public string LogException(string message, Exception ex)
        {
            string uniqueId = GetUniqueId();
            ThreadContext.Properties["UId"] = uniqueId;
            logger.Error(message, ex);
            return uniqueId;
        }

        public void LogInfo(string message)
        {
            if (logger.IsInfoEnabled)
            {
                ThreadContext.Properties["UId"] = GetUniqueId();
                logger.Info(message);
            }
        }

        private object uniqueIdLock = new object();
        private long lastTicks;
        private const long baseTicks = 633347424000000000; // 1/1/2008

        private string GetUniqueId()
        {
            lock (uniqueIdLock)
            {
                long ticks = DateTime.Now.Ticks - baseTicks;
                if (ticks == lastTicks)
                {
                    ticks++;
                }
                lastTicks = ticks;
                return "" + ticks;
            }
        }
    }
}
